/*
********************************************************************************
*
*	file : mian.c
*
********************************************************************************
*/
#include "ff.h"
#include "app_update.h"
#include "common.h"

extern FATFS fatfs;
extern FIL file;

uint16_t bytesWritten, bytesToWrite;
FRESULT res;

/*******************************************************************************
* @brief  file_open :
* \param[in] none
* \retval: 0-err, 1-ok
*******************************************************************************/
uint16_t ap_file_open(const char *file_name, uint8_t mode)
{
	uint8_t st;

	st = 0;

	switch (mode)
	{
	case FIL_OPEN_R:
		if (f_open(&file, file_name, FA_READ) == FR_OK)
			st = 1;
		break;
	case FIL_OPEN_W:
		if (f_open(&file, file_name, FA_WRITE | FA_OPEN_ALWAYS) == FR_OK)
			st = 1;
		break;
	case FIL_OPEN_WA:
		if (f_open(&file, file_name, FA_WRITE | FA_CREATE_ALWAYS) == FR_OK)
			st = 1;
		break;
	default:
		st = 0;
		break;
	}

	return st;
}

/*******************************************************************************
* @brief  ap_file_read :
* \param[in] none
* \retval: none
*******************************************************************************/
uint16_t ap_file_read(void *buff, uint16_t len)
{
	uint32_t len_back = 0;

	if (f_read(&file, buff, len, &len_back) != FR_OK)
	{
		len_back = 0;
	}

	return len_back;
}

/*******************************************************************************
* @brief  ap_file_write :
* \param[in] none
* \retval: none
*******************************************************************************/
uint16_t ap_file_write(void *buff, uint16_t len)
{
	uint32_t len_back = 0;

	if (f_write(&file, buff, len, &len_back) != FR_OK)
	{
		len_back = 0;
	}

	return len_back;
}

/*******************************************************************************
* @brief  ap_file_seek:
* \param[in] none
* \retval: none
*******************************************************************************/
uint32_t ap_file_seek(uint32_t site)
{
	if (f_lseek(&file, site) != FR_OK)
	{
		return 0;
	}

	return file.obj.objsize;
}

/*******************************************************************************
* @brief  ap_file_seek_end :
* \param[in] none
* \retval: none
*******************************************************************************/
uint32_t ap_file_size_get(void)
{
	return file.obj.objsize;
}

/*******************************************************************************
* @brief  file_open :
* \param[in] none
* \retval: none
*******************************************************************************/
uint16_t ap_file_close(void)
{
	f_close(&file);

	return 1;
}
